import 'package:flutter/material.dart';
import 'package:logging/logging.dart';

final _log = Logger('NavObserver');

final NavObserver navObserver = NavObserver();

// previousRoute指的是栈中相对的前一个route
class NavObserver extends NavigatorObserver {
  NavObserver._internal();

  static final NavObserver _singleton = NavObserver._internal();

  factory NavObserver() => _singleton;

  final List<Route<dynamic>> _routeStack = [];

  Route<dynamic> get currentRoute {
    if (_routeStack.isNotEmpty) {
      return _routeStack.last;
    }
    return null;
  }

  @override
  void didPush(Route<dynamic> route, Route<dynamic> previousRoute) {
    _routeStack.add(route);
    _log.info(
        "didPush route: ${route?.settings?.name} previousRoute: ${previousRoute?.settings?.name}");
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic> previousRoute) {
    if (_routeStack.isNotEmpty) {
      _routeStack.removeLast();
    }
    _log.info("didPop route: ${route?.settings?.name} previousRoute: ${previousRoute?.settings?.name}");
  }

  @override
  void didRemove(Route route, Route previousRoute) {
    _routeStack.removeWhere((element) => element?.settings?.name == route?.settings?.name);
    _log.info(
        "didRemove route: ${route?.settings?.name} previousRoute: ${previousRoute?.settings?.name}");
  }

  @override
  void didReplace({Route newRoute, Route oldRoute}) {
    if (_routeStack.isNotEmpty) {
      _routeStack.removeLast();
    }
    _routeStack.add(newRoute);
    _log.info("didReplace newRoute: ${newRoute?.settings?.name} oldRoute: ${oldRoute?.settings?.name}");
  }
}
